import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/ess_tab_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/func_utils.dart';
import '../../../../services/device/device_sevices.dart';
import '../../site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'add_ess_unit.dart';
import 'dynamic_monitor_widget.dart';
///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2024年05月17日 09:15
class EssMonitorWidget extends StatefulWidget {
  final Map map;
  final int index;
  final int siteId;
  final Function() switchCallback;
  const EssMonitorWidget(this.map, this.index, this.siteId, this.switchCallback,
      {super.key});

  @override
  State<EssMonitorWidget> createState() => EssMonitorWidgetState();
}

class EssMonitorWidgetState extends State<EssMonitorWidget>
    with TickerProviderStateMixin {
  int selectedIndex = 0;
  Map map = {};
  late TabController tabController = TabController(length: 2, vsync: this);
  DeviceServices services = Get.put(DeviceServices());
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    map = widget.map;
    tabController.addListener(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 10,left: 16,right: 16),
          clipBehavior: Clip.hardEdge,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colour.white,
          ),
          padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
          height: 50,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(ResKey.siteSettingObserverPhotovoltaicObserverStatus.tr,
                  style:
                      ytTextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
              CupertinoSwitch(
                  activeColor: Colour.primaryColor,
                  value: (map['flag'] != null && map['flag'] == true)
                      ? true
                      : false,
                  onChanged: FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingMonitorSettingEssStatus])?(isOpen) {
                    if (!isOpen) {
                      BrnDialogManager.showConfirmDialog(
                        context,
                        cancel: ResKey.cancel.tr,
                        confirm: ResKey.confirm.tr,
                        title: ResKey.siteSettingObserverTurnoff.tr,
                        message: ResKey.siteSettingObserverTurnoffTip.tr,
                        onCancel: () => Get.back(),
                        onConfirm: () {
                          Log.d('发送网络请求关闭页面');
                          obsStatusChange(isOpen, map);
                          Get.back();
                        },
                      );
                    } else {
                      obsStatusChange(isOpen, map);
                    }
                  }:null)
            ],
          ),
        ),
        Gaps.vGap10,
        if (map['flag'].toString() == 'true')
          EssTabWidget(
            selectedIndex,
            (index) {
              if (selectedIndex == index) return;
              tabController.animateTo(index);
              setState(() {
                selectedIndex = index;
              });
            },
            firstTitle: ResKey.eSSUnitManager.tr,
            secondTitle: ResKey.monitoringItems.tr,
          ),
        if (map['flag'].toString() == 'true')
          Expanded(
              child: TabBarView(controller: tabController,
           physics: const NeverScrollableScrollPhysics(),
           children: [
            KeepAliveWrapper(AddEssUnitWidget(siteId: widget.siteId)),
            KeepAliveWrapper(ListView(
              children: [
                DynamicMonitorWidget(
                    map, 2, (dataList, type) => tapEditHandler(dataList, type))
              ],
            )),
          ]))
      ],
    );
  }

  ///监测点的开关状态切换
  obsStatusChange(bool isOpen, Map map) async {
    var param = {
      'siteId': widget.siteId.toString(),
      'type': map['id'],
      'flag': (isOpen).toString()
    };
    Log.d('param==$param');
    showLoading(toast: ResKey.loading.tr);
    var result =
        await services.siteObserverObserverStatus(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      map['flag'] = isOpen;
    }
    widget.switchCallback();
    setState(() {});
    Log.d('result==$result');
  }

  ///点击编辑按钮跳转
  tapEditHandler(List<dynamic>? dataList, int type) {
    Get.toNamed(RouterPath.siteObserverDetail, arguments: {
      'siteId': widget.siteId,
      'dataList': dataList,
      'type': type
    });
  }
}
